package net.sureon.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.biz.CompanyBO;
import net.sureon.biz.CompanyMgr;
import net.sureon.biz.TitaonMailHelper;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.exception.SureonException;
import net.sureon.common.security.SecurityUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * 处理忘记密码类
 * 
 * @author Administrator
 * 
 */
/*
 * 第一次进入跳转到填写信息，以确认该用户是否存在 当用户输入信息提交跳转到这个页面后，知道用户的密码，并mail给用户
 */
public class ForgetPassword implements Controller {
	private static final Log logger = LogFactory.getLog(ForgetPassword.class);

	private UserMgr userMgr;
	private CompanyMgr companyMgr;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String forgetPassword = request.getParameter("forgetPassword");
		if ("true".equals(forgetPassword)) {
			try {
				String siteUrl = request.getParameter("siteURL");
				String userName = request.getParameter("userName");
				CompanyBO company = companyMgr.getCompany(siteUrl);
				UserBO user = userMgr.getUserByUsername(company.getCompanyID(),
						userName);
				String email = request.getParameter("realName");
				if (user.getUserVO().getRealName() != null && user.getUserVO().getRealName().equalsIgnoreCase(email)) {
					String initPassword = SecurityUtils.generateRandomString(6,
							8);
					TitaonMailHelper.getInstance().sendUserReminderMail(
							TitaonMailHelper.MAIL_NAME_RESET_PASSWORD, company,
							user, initPassword);
					// 将新的密码写入数据库，并在登录页面给予提示
					String newPassword = SecurityUtils.generateSHA512Hash(user
							.getUserVO().getSalt()
							+ ":" + initPassword);
					user.getUserVO().setPassword(newPassword);
					userMgr.updateUser(user);

					response.sendRedirect(request.getContextPath()
							+ "/index.do?sendMail=true");
					return null;
				}
			} catch (SureonException e) {
				logger.error(e);
			}
			request.setAttribute("errMsg", "验证信息填写有误！");
		}

		return new ModelAndView("forgetPassword");
	}

	public UserMgr getUserMgr() {
		return userMgr;
	}

	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}

	/**
	 * @return the companyMgr
	 */
	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}

	/**
	 * @param companyMgr
	 *            the companyMgr to set
	 */
	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}

}